﻿using Hidistro.Entities.Sales;
using Hidistro.Membership.Context;
using Hidistro.SaleSystem.Shopping;
using Hidistro.UI.Common.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.HtmlControls;
using Hidistro.UI.SaleSystem.Tags;
using System.Web.UI.WebControls;
using Hidistro.Core;
using wnxd.javascript;
using System.Reflection;
using System.Web.UI;
using System.Data;
using Hidistro.Entities.Commodities;
using Hidistro.SaleSystem.Catalog;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Hidistro.SqlDal.Members;
using System.Web;

namespace Hidistro.UI.SaleSystem.CodeBehind
{
    public class wnxd_ShoppingCart : AscxTemplatedWebControl
    {
        HtmlGenericControl isLogin, ShoppingCart, PromotionsList, wnxd_wdgz, wnxd_wdgz_list;
        wnxd_ShoppingCart_ProductList ProductList;
        wnxd_ShoppingCart_Promotions Promotions;
        Label Quantity, Total, Amount;
        Literal promotionname;
        wnxd_Shopping_LiList cainixihuan, favorites, history;
        public json List = new json();
        IList<string> NotSelect;
        protected override void AttachChildControls()
        {
            if (!string.IsNullOrEmpty(this.Page.Request["wnxd_Ajax"]))
            {
                this.wnxd_Ajax(this.Page.Request["wnxd_Ajax"]);
            }
            if (!string.IsNullOrEmpty(this.Page.Request.Form["list"]))
            {
                dynamic t = this.List = new json(this.Page.Request.Form["list"]);
                this.NotSelect = t;
            }
            this.isLogin = (HtmlGenericControl)this.FindControl("isLogin");
            this.ShoppingCart = (HtmlGenericControl)this.FindControl("ShoppingCart");
            this.PromotionsList = (HtmlGenericControl)this.FindControl("PromotionsList");
            this.ProductList = (wnxd_ShoppingCart_ProductList)this.FindControl("productlist");
            this.Promotions = (wnxd_ShoppingCart_Promotions)this.FindControl("promotions");
            this.Quantity = (Label)this.FindControl("Quantity");
            this.Total = (Label)this.FindControl("Total");
            this.Amount = (Label)this.FindControl("Amount");
            this.wnxd_wdgz = (HtmlGenericControl)this.FindControl("wnxd_wdgz");
            this.wnxd_wdgz_list = (HtmlGenericControl)this.FindControl("wnxd_wdgz_list");
            this.cainixihuan = (wnxd_Shopping_LiList)this.FindControl("cainixihuan");
            this.favorites = (wnxd_Shopping_LiList)this.FindControl("favorites");
            this.history = (wnxd_Shopping_LiList)this.FindControl("history");
            this.promotionname = (Literal)this.FindControl("promotionname");
            if (!HiContext.Current.User.IsAnonymous)
            {
                this.wnxd_wdgz.Visible = this.wnxd_wdgz_list.Visible = !(this.isLogin.Visible = false);
                this.favorites.DataSource = ProductBrowser.GetFavorites();
                this.favorites.DataBind();
            }
            ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart(this.NotSelect);
            if (shoppingCart == null)
            {
                this.ShoppingCart.Visible = false;
                ShoppingCartProcessor.ClearShoppingCart();
            }
            else
            {
                if (shoppingCart.LineItems.Count > 0)
                {
                    List<PromotionShopInfo> Promotions = new List<PromotionShopInfo>();
                    List<ShoppingCartItemInfo> ShopList = new List<ShoppingCartItemInfo>(shoppingCart.LineItems);
                    if (shoppingCart.ReducedPromotionInfo != null)
                    {
                        for (int i = 0; i < shoppingCart.ReducedPromotionInfo.Length; i++)
                        {
                            if (shoppingCart.ReducedPromotionInfo[i].ProductIds != null && shoppingCart.ReducedPromotionInfo[i].ProductIds.Length > 0)
                            {
                                List<ShoppingCartItemInfo> t = new List<ShoppingCartItemInfo>();
                                int n = 0;
                                while (n < ShopList.Count)
                                {
                                    if (shoppingCart.ReducedPromotionInfo[i].ProductIds.Contains(ShopList[n].ProductId))
                                    {
                                        t.Add(ShopList[n]);
                                        ShopList.RemoveAt(n);
                                    }
                                    else n++;
                                }
                                PromotionShopInfo pi = new PromotionShopInfo() { Name = shoppingCart.ReducedPromotionInfo[i].Name, Condition = shoppingCart.ReducedPromotionInfo[i].Condition, DiscountValue = shoppingCart.ReducedPromotionInfo[i].DiscountValue, Total = shoppingCart.ReducedPromotionInfo[i].Total, ShopInfo = t };
                                Promotions.Add(pi);
                            }
                        }
                    }
                    if (shoppingCart.SendGiftPromotionInfo != null)
                    {
                        for (int i = 0; i < shoppingCart.SendGiftPromotionInfo.Length; i++)
                        {
                            if (shoppingCart.SendGiftPromotionInfo[i].ProductIds != null && shoppingCart.SendGiftPromotionInfo[i].ProductIds.Length > 0)
                            {
                                List<ShoppingCartItemInfo> t = new List<ShoppingCartItemInfo>();
                                int n = 0;
                                while (n < ShopList.Count)
                                {
                                    if (shoppingCart.SendGiftPromotionInfo[i].ProductIds.Contains(ShopList[n].ProductId))
                                    {
                                        t.Add(ShopList[n]);
                                        ShopList.RemoveAt(n);
                                    }
                                    else n++;
                                }
                                PromotionShopInfo pi = new PromotionShopInfo() { Name = shoppingCart.SendGiftPromotionInfo[i].Name, Condition = shoppingCart.SendGiftPromotionInfo[i].Condition, DiscountValue = shoppingCart.SendGiftPromotionInfo[i].DiscountValue, Total = shoppingCart.ReducedPromotionInfo[i].Total, ShopInfo = t };
                                Promotions.Add(pi);
                            }
                        }
                    }
                    if (shoppingCart.SentTimesPointPromotionInfo != null)
                    {
                        for (int i = 0; i < shoppingCart.SentTimesPointPromotionInfo.Length; i++)
                        {
                            if (shoppingCart.SentTimesPointPromotionInfo[i].ProductIds != null && shoppingCart.SentTimesPointPromotionInfo[i].ProductIds.Length > 0)
                            {
                                List<ShoppingCartItemInfo> t = new List<ShoppingCartItemInfo>();
                                int n = 0;
                                while (n < ShopList.Count)
                                {
                                    if (shoppingCart.SentTimesPointPromotionInfo[i].ProductIds.Contains(ShopList[n].ProductId))
                                    {
                                        t.Add(ShopList[n]);
                                        ShopList.RemoveAt(n);
                                    }
                                    else n++;
                                }
                                PromotionShopInfo pi = new PromotionShopInfo() { Name = shoppingCart.SentTimesPointPromotionInfo[i].Name, Condition = shoppingCart.SentTimesPointPromotionInfo[i].Condition, DiscountValue = shoppingCart.SentTimesPointPromotionInfo[i].DiscountValue, Total = shoppingCart.ReducedPromotionInfo[i].Total, ShopInfo = t };
                                Promotions.Add(pi);
                            }
                        }
                    }
                    this.ProductList.DataSource = ShopList;
                    this.ProductList.DataBind();
                    this.promotionname.Text = shoppingCart.ReducedPromotionName;
                    if (Promotions.Count > 0)
                    {
                        this.PromotionsList.Visible = true;
                        this.Promotions.DataSource = Promotions;
                        this.Promotions.DataBind();
                    }
                }
                this.Quantity.Text = shoppingCart.GetQuantity().ToString();
                this.Total.Text = Globals.FormatMoney(shoppingCart.GetTotal());
                this.Amount.Text = Globals.FormatMoney(shoppingCart.ReducedPromotionAmount);
            }
            this.cainixihuan.DataSource = this.GetCaiNiXiHuan();
            this.cainixihuan.DataBind();
            this.history.DataSource = this.GetHistory();
            this.history.DataBind();
        }
        protected override void OnInit(EventArgs e)
        {
            this.Page.Response.Redirect("http://order.x-juse.com/ShoppingCart.aspx?sdomain=" + HttpUtility.UrlEncode("http://" + this.Page.Request.Url.Authority));
            if (this.SkinName == null)
            {
                this.SkinName = "Skin-wnxd_ShoppingCart.ascx";
            }
            base.OnInit(e);
        }
        private void wnxd_Ajax(string action)
        {
            MethodInfo mi = this.GetType().GetMethod(action, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (mi != null)
            {
                mi.Invoke(this, new object[] { this.Page });
                this.Page.Response.End();
            }
        }
        private void UpdateNum(Page Page)
        {
            int num;
            json json = new json(new { error = true });
            if (!int.TryParse(Page.Request.Form["num"], out num))
            {
                json["msg"] = "购买数量必须为整数";
            }
            else if (num <= 0)
            {
                json["msg"] = "购买数量必须为大于0的整数";
            }
            else
            {
                if (ShoppingCartProcessor.GetSkuStock(Page.Request.Form["SkuId"]) < num)
                {
                    json["msg"] = "该商品库存不够";
                }
                else
                {
                    ShoppingCartProcessor.UpdateLineItemQuantity(Page.Request.Form["SkuId"], num);
                    json["error"] = false;
                    dynamic t = new json(this.Page.Request.Form["list"]);
                    this.NotSelect = t;
                    ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart(this.NotSelect);
                    json["total"] = shoppingCart.GetTotal();
                    json["quantity"] = shoppingCart.GetQuantity();
                    json["amount"] = shoppingCart.ReducedPromotionAmount;
                }
            }
            Page.Response.Write(json);
        }
        private void UpdateList(Page Page)
        {
            json json = new json(new { error = true });
            dynamic t = new json(Page.Request.Form["list"]);
            this.NotSelect = t;
            ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart(this.NotSelect);
            json["error"] = false;
            json["total"] = shoppingCart.GetTotal();
            json["quantity"] = shoppingCart.GetQuantity();
            json["amount"] = shoppingCart.ReducedPromotionAmount;
            Page.Response.Write(json);
        }
        private void DeleteList(Page Page)
        {
            json json = new json(new { error = true });
            json list = new json(Page.Request.Form["list"]);
            if (list == js.undefined || list.length == 0)
            {
                json["msg"] = "请选择要清除的商品";
            }
            else
            {
                for (int i = 0; i < list.length; i++)
                {
                    ShoppingCartProcessor.RemoveLineItem(list[i].Value);
                }
                json["error"] = false;
            }
            Page.Response.Write(json);
        }
        Database database = DatabaseFactory.CreateDatabase();
        private DataTable sql_call(string sql)
        {
            using (DbCommand cmd = database.GetSqlStringCommand(sql))
            using (IDataReader reader = database.ExecuteReader(cmd))
            {
                return DataHelper.ConverDataReaderToDataTable(reader);
            }
        }
        private DataTable GetCaiNiXiHuan()
        {
            IList<int> browedProductList = BrowsedProductQueue.GetBrowedProductList();
            if (browedProductList.Count == 0) return null;
            string pids = "";
            for (int i = 0; i < browedProductList.Count; i++)
            {
                if (i > 0)
                {
                    pids += ",";
                }
                pids += browedProductList[i];
            }
            Member user = HiContext.Current.User as Member;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("select top({0}) ProductId,ThumbnailUrl310,ProductName,MarketPrice,SkuId,Stock,MonthlySales,Review,CategoryUrl,", browedProductList.Count);
            if (user != null)
            {
                int discount = new MemberGradeDao().GetMemberGrade(user.GradeId).Discount;
                sb.AppendFormat(" (CASE WHEN (SELECT COUNT(*) FROM Hishop_SKUMemberPrice WHERE SkuId = b.SkuId AND GradeId = {0}) = 1", user.GradeId);
                sb.AppendFormat(" THEN (SELECT MemberSalePrice FROM Hishop_SKUMemberPrice WHERE SkuId = b.SkuId AND GradeId = {0}) ELSE SalePrice*{1}/100 END) AS SalePrice", user.GradeId, discount);
            }
            else
            {
                sb.Append("SalePrice");
            }
            sb.AppendFormat(" from vw_Hishop_BrowseProductList as b where ProductId not in ({0}) and MainCategoryPath in (select MainCategoryPath from Hishop_Products where ProductId in ({0})) order by newid()", pids);
            return this.sql_call(sb.ToString()); ;
        }
        private DataTable GetHistory()
        {
            IList<int> browedProductList = BrowsedProductQueue.GetBrowedProductList();
            if (browedProductList.Count == 0) return null;
            return ProductBrowser.GetVistiedProducts(browedProductList);
        }
    }
}
